\subsection{Crypto \statusgreen}\label{spec:format:crypto}

This section describes the crypto primitives used throughout the specification. They  are exposed as  buzz built-in  functions.
The modules are hashing, random number generation, key derivation, symmetric and asymmetric encryption (ECIES), mining (i.e., finding a nonce), elliptic curve key generation, digital signature (ECDSA), Diffie--Hellman shared secret (ECDH) and Cauchy-Reed-Solomon  (CRS) erasure coding.

Some of the built-in crypto primitives (notably, sha3 hash, and ECDSA ecrecover) are replicating crypto functionality of the Ethereum VM. These are defined here with the help of ethereum api calls to a smart contract. This smart contract just implements the primitives of "buzz" and only has read methods.

\subsubsection{Hashing}

The base hash function implements Keccak256 hash as used in Ethereum.

\begin{definition}[Hashing]\label{def:hash}
\begin{lstlisting}[language=buzz1]
// /crypto

define function hash @input []byte
    ?and/with @suff
    return segment
as
    ethereum/call "sha3" with @input append= @suff
         on context contracts "buzz" 
\end{lstlisting}
\end{definition}  


\subsubsection{Random number generation}

\begin{definition}[Random number generation]\label{def:rng}
\begin{lstlisting}[language=buzz1]
// /crypto

define function random type 
    return [@type size]byte 

\end{lstlisting}
\end{definition}    


\subsubsection{Scrypt key derivation}

The crypto key derivation function implements \lstinline{scrypt} \cite{percival2009stronger}.

\begin{definition}[Scrypt key derivation]\label{def:scrypt}
\begin{lstlisting}[language=buzz1]
// /crypto

define type salt as [segment size]byte

define type key as [segment size]byte

// params for scrypt key derivation function
// scrypt.key(password, salt, n, r, p, 32) to generate key

define type kdf
    n int // 262144
    r int // 8
    p int // 1

define function scrypt from @password
    with   salt 
    using  kdf
    return key

\end{lstlisting}
\end{definition}  

\subsubsection{Mining helper}

This module provides a very simple helper function that finds a nonce that when given as the single argument to a mining function returns true.

\begin{definition}[Mining a nonce]\label{def:mine}
\begin{lstlisting}[language=buzz1]
// /crypto

define type nonce as [segment size]byte

define function mine @f function of nonce return bool
as
    @nonce = random key
    return @nonce if call @f @nonce
    self @f
    
\end{lstlisting}
\end{definition}  

\subsubsection{Symmetric encryption}

Symmetric encryption uses a modified blockcipher with 32 byte blocksize in counter mode.
The segment keys are generated by hashing the chunk-specific encryption key with the counter and hash that again. This second step is required so that a segment can be selectively disclosed in a 3rd party provable way yet without compromising the security of the rest of the chunk.

The module provides input length preserving blockcipher encryption.

\begin{definition}[Blockcipher]\label{def:crypt}
\begin{lstlisting}[language=buzz1]
// /crypto

// two-way (en/de)crypt function for segment
define function crypt.segment segment
    with key
    at @i uint8
as
    hash @key and @i        // counter mode 
        hash                // extra hashing
        to @segment length  // chop if needed
        xor @segment        // xor key with segment

// two-way (en/de)crypt function for arbitrary length 
define function crypt @input []byte
    with key
    return [@input length]byte
as
    @segments = @input each segment size    // iterate segments of input
        go crypt.segment at @i++ with @key  // concurrent crypt on segments
    return wait for @segments               // wait for results
        join                                // join (en/de)crypted segments
        
\end{lstlisting}
\end{definition}    

\subsubsection{Elliptic curve keys}

Public key cryptography is the same as in Ethereum, it uses the secp256k1 elliptic curve.  


\begin{definition}[Elliptic curve key generation]\label{def:ec-keys}
\begin{lstlisting}[language=buzz1]
// /crypto
define type pubkey  as [64]byte
define type keypair
    privkey [32]byte
    pubkey
    
define type address as [20]byte

define function address pubkey
    return address
as 
    hash pubkey 
        from 12

define function generate 
p    ?using entropy
as
    @entropy = random segment if no @entropy
    http/get "signer/generate?entropy=" append @entropy 
        as keypair

\end{lstlisting}
\end{definition}    

\subsubsection{Asymmetric encryption}

Asymmetric encryption implements ECIES based on  the secp256k1 elliptic curve. 
%  TODO: this needs more detail

\begin{definition}[Asymmetric encryption]\label{def:asymmetric-encryption}
\begin{lstlisting}[language=buzz1]
// /crypto

define function encrypt @input []byte 
    for pubkey
    return [@input length]byte

define function decrypt @input []byte 
    with keypair
    return [@input length]byte

\end{lstlisting}
\end{definition}  


\subsubsection{Signature}

Crypto's  built-in signature module implements secp2156k1 elliptic curve based ECDSA. The actual signing happens in the external signer running as a separate process (possibly within the secure enclave). As  customary  in Ethereum, the  signature is represented and serialised using the r/s/v format,

\begin{definition}[Signature]\label{def:signature}
\begin{lstlisting}[language=buzz1]
// /crypto

define type signature
    r segment
    s segment
    v uint8
    signer private keypair
    

define type doc 
    preamble []byte
    context  []byte
    asset    segment
    
define function sign @input []byte 
    by keypair
    return signature
as
    @doc = doc{ "swarm signature", context caller, @input }
    @sig = http/get "signer/sign?text=" append @doc 
        append "&account=" append @keypair pubkey address
            as signature 
    @sig signer = @keypair
    @sig
    
define function recover signature
    with @input []byte
    from @caller []byte
    return pubkey
as
    @doc =  doc{ "swarm signature", @caller, @input } as bytes
    ethereum/call "ecrecover" with 
        on context contracts "buzz" 
            as pubkey

\end{lstlisting}
\end{definition}  


\subsubsection{Diffie-Hellmann shared secret}

The shared secret module implements elliptic curve based Diffie--Helmann shared secret (ECDH) using the usual secp256k1 elliptic curve.
The actual DH comes from the external signer which is then hashed together with a salt.

\begin{definition}[Shared secret]\label{def:dh}
\begin{lstlisting}[language=buzz1]
// /crypto

define function shared.secret between keypair
    and pubkey
    using salt
    return [segment size]byte
as
    http/get "signer/dh?pubkey=" append @pubkey append "&account=" @keypair address
        hash with @salt

\end{lstlisting}
\end{definition}  

\subsubsection{Erasure coding}\label{spec:format:erasure}

Erasure coding interface provides wrappers \lstinline{extend/repair} for the encoder/decoder that work directly on a list of chunks.%
%
\footnote{Cauchy-Reed-Solomon erasure codes based on \url{https://github.com/klauspost/reedsolomon}.
}

Assuming $n$ out of $m$ coding.
\lstinline{extend} takes a list of $n$ data chunks and an argument for the number of required parities. It returns the parity chunks only.
\lstinline{repair} takes a list of $m$ chunks (extended with \emph{all} parities) and an argument for the number of parities $p=m-n$, that designate the last $p$ chunks as parity chunks. It returns the list of $n$ repaired data chunks only.
The encoder does not know which parts are invalid, so missing or invalid chunks should be set to \lstinline{nil} in the argument to repair.
If parity chunks are needed to be repaired, you call \lstinline{repair @chunks with @parities; extend with @parities}

\begin{definition}[CRS erasure code interface definition]\label{def:crs}
\begin{lstlisting}[language=buzz1]
// /crypto/crs

define function extend @chunks []chunk 
    with @parities uint
    return [@parities]chunk

define function repair @chunks []chunk   
    with @parities uint
   return [@chunks length - @parities]chunk

\end{lstlisting}
\end{definition}

\begin{definition}[CRS erasure coding parameters]\label{def:crs-params}
\begin{lstlisting}[language=buzz1]
// /crypto/crs
define strategy as "race"|"fallback"|"disabled"

define type params 
    parities uint
    strategy 
     
\end{lstlisting}
\end{definition}


\subsection{State store \statusgreen}\label{spec:format:statestore}
% \input{specs/api/statestore.tex}

\begin{definition}[State store]\label{def:state-store}
\begin{lstlisting}[language=buzz1]
// /statestore

define type key []byte
define type db  []byte
define type value []byte

define function create db

define function destroy db

define function put value
    to db
    on key
    
define function get key 
    from db
    return value
\end{lstlisting}
\end{definition}


\subsection{Local context and configuration \statusgreen}\label{spec:format:local}
% \input{specs/api/local.tex}


\begin{definition}[Context]\label{def:scontext}
\begin{lstlisting}[language=buzz1]
// /context

define type contract as "buzz"|"chequebook"|"postage"|""

define type context
    contracts [contract]ethereum/address 
\end{lstlisting}
\end{definition}